﻿using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.API.Controllers.Base;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.IService.JJFlow.BPM;
using Jinjia.Approve.Model.Input.JJFlow;
using Jinjia.Approve.Model.VM.JJFlow;
using Jinjia.Approve.Model.VM.JJFlow.Request;
using Jinjia.Core.BaseInfrastructure.StorageModel.Model;
using Jinjia.Core.Transaction.Service;
using Microsoft.AspNetCore.Mvc;

namespace Jinjia.Approve.API.Controllers
{
    public class JJFlowController : BaseController
    {
        private readonly IJJFlowService _jjFlowService;
        private readonly IJJFlowTemplateService _jjFlowTemplateService;
        private readonly IJJFlowMappingService _jjFlowMappingService;
        private readonly IJJFlowDicCodeService _jjFlowDicCodeService;
        private readonly IJJFlowBpmXMLService _jjFlowBpmXmlService;
        private readonly ITransactionCAP _transactionCap;

        public JJFlowController(IJJFlowService jjFlowService,
            IJJFlowTemplateService jjFlowTemplateService,
            IJJFlowMappingService jjFlowMappingService,
            IJJFlowDicCodeService jjFlowDicCodeService,
            IJJFlowBpmXMLService jjFlowBpmXmlService,
            IDistributedTransactionService distributedTransactionService)
        {
            _jjFlowService = jjFlowService;
            _jjFlowTemplateService = jjFlowTemplateService;
            _jjFlowMappingService = jjFlowMappingService;
            _jjFlowDicCodeService = jjFlowDicCodeService;
            _jjFlowBpmXmlService = jjFlowBpmXmlService;
            _transactionCap = distributedTransactionService.CreateCAP();
        }

        /// <summary>
        /// 发起审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateRequest request)
        {
            var nodeInfo = await _jjFlowService.Create(request);
            _transactionCap.Publish(new JJFlowOperate
            {
                InstanceId = nodeInfo.instance_id
            });
            return Success(nodeInfo);
        }

        /// <summary>
        /// 通过
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Approve([FromBody] CreateRequest request)
        {
            var nodeInfo = await _jjFlowService.Approve(request);
            _transactionCap.Publish(new JJFlowOperate
            {
                InstanceId = nodeInfo.instance_id
            });
            return Success(nodeInfo);
        }

        /// <summary>
        /// 自动审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AutoApprove([FromBody] AutoApproveRequest request)
        {
            var instanceId = await _jjFlowService.AutoApprove(request);
            if (instanceId.HasValue)
            {
                _transactionCap.Publish(new JJFlowOperate
                {
                    InstanceId = instanceId.Value
                });
            }
            return Success();
        }

        /// <summary>
        /// 驳回审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Reject([FromBody] CreateRequest request)
        {
            var instanceId = await _jjFlowService.Reject(request);
            _transactionCap.Publish(new JJFlowOperate
            {
                InstanceId = instanceId
            });
            return Success();
        }

        /// <summary>
        /// 撤回审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Recall([FromBody] ReCallRequest request)
        {
            var instanceId = await _jjFlowService.Recall(request);
            _transactionCap.Publish(new JJFlowOperate
            {
                InstanceId = instanceId
            });
            return Success();
        }

        /// <summary>
        /// 流程轨迹
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetFlowTrackList([FromQuery] CreateRequest request)
        {
            var jjFlowTrackVms = await _jjFlowService.GetFlowTrackList(request);
            return Success(jjFlowTrackVms);
        }

        /// <summary>
        /// 查询已完成审批节点列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetCompletedNodeList([FromQuery] CreateRequest request)
        {
            var jjFlowTrackVms = await _jjFlowService.GetCompletedNodeList(request);
            return Success(jjFlowTrackVms);
        }

        /// <summary>
        /// 记录模块查阅日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ViewLog([FromQuery] CreateRequest request)
        {
            var result = await _jjFlowService.ViewedLog(request);
            return Success("", result);
        }

        /// <summary>
        /// 复制审批流
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CopyFlowTrack([FromQuery] CopyJJFlowRequest request)
        {
            var result = await _jjFlowService.CopyJJFlowTrack(request);
            if (result.IsSuccess)
            {
                return Success(result.Content, result.Message);
            }
            else
            {
                return Error(result.Message);
            }
        }

        /// <summary>
        /// 获取用户是否有待审核数据权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserPower([FromQuery] QueryRequest request)
        {
            var result = await _jjFlowService.GetUserPower(request);
            return Success(result);
        }

        /// <summary>
        /// 浏览日志记录（可通用）
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetViewedLog([FromQuery] CreateRequest request)
        {
            var result = await _jjFlowService.GetViewedLog(request);
            return Success(result);
        }

        /// <summary>
        /// 待办审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserBizOrderId([FromQuery] QueryRequest request)
        {
            var nodeInfo = await _jjFlowService.GetUserBizOrderId(request);
            return Success(nodeInfo);
        }

        /// <summary>
        /// 首页 待办 汇总页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMyTodoList([FromQuery] SearchConditionBaseInput input)
        {
            var todoList = await _jjFlowService.GetMyTodoList(input);
            return Success(todoList);
        }

        /// <summary>
        /// 首页 待办 汇总页的条数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMyTodoListCount()
        {
            var todoList = await _jjFlowService.GetMyTodoListCount();
            return Success(todoList);
        }


        /// <summary>
        /// 首页 待办详情页 + 我提交的审批 的详情页 总共2个
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMyTodoListDetail([FromQuery] GetToDoListDetailByTab input)
        {
            var todoListDetail = await _jjFlowService.GetTodoListDetailForCurrentUser(input);
            return Success(todoListDetail);
        }

        /// <summary>
        /// 用户输入url信息，模糊搜索出该url在erpa_function_tbl表的信息，并返回id和url给前端
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> SearchByUrl(string url)
        {
            var urlInfo = await _jjFlowService.SearchByUrl(url);
            return Success(urlInfo);
        }

        /// <summary>
        /// 我已审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserProcessedBizOrderId([FromQuery] QueryRequest request)
        {
            var nodeInfo = await _jjFlowService.GetUserProcessedBizOrderId(request);
            return Success(nodeInfo);
        }

        /// <summary>
        /// 我提交的审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserCreateApplyBizOrderId([FromQuery] QueryRequest request)
        {
            var nodeInfo = await _jjFlowService.GetUserCreateApplyBizOrderId(request);
            return Success(nodeInfo);
        }
        
        /// <summary>
        /// 全部审批-我提交的审批+待办审批+我已审批
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserAllApproveBizOrderIdAsync([FromQuery] QueryRequest request)
        {
            // 待办审批
            var toDoList = await _jjFlowService.GetUserBizOrderId(request);
            // 我已审批
            var processedList = await _jjFlowService.GetUserProcessedBizOrderId(request);
            // 提交的审批
            var createApplyList = await _jjFlowService.GetUserCreateApplyBizOrderId(request);

            return Success(toDoList.Union(processedList).Union(createApplyList));
        }

        /// <summary>
        /// 审批转交
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PassOn([FromBody] PassOnRequest request)
        {
            await _jjFlowService.PassOn(request);
            return Success();
        }

        /// <summary>
        /// 审批转交（根据审批单据进行转交）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> TransferFlowsAsync([FromBody] TransferFlowsInput input)
        {
            var validationResult = await new TransferFlowsInputValidator().ValidateAsync(input);

            if (validationResult.IsValid)
            {
                return Success(await _jjFlowService.TransferFlowsAsync(input));
            }

            return ValidationError(validationResult.Errors);
        }

        /// <summary>
        /// 审批退回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SendBack([FromBody] SendBackRequest request)
        {
            var sendBack = await _jjFlowService.SendBack(request);
            return Success(sendBack);
        }

        /// <summary>
        /// 流程模板列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetTemplatePageList([FromQuery] JJTemplateSearchCondition query)
        {
            var pageListSearchResultVm = await _jjFlowTemplateService.GetTemplatePageList(query);
            return Success(pageListSearchResultVm);
        }

        /// <summary>
        /// 通过id获取流程模板明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetTemplateDetail([FromQuery] int id)
        {
            var jjTemplateSignleViewModel = await _jjFlowTemplateService.GetTemplateDetail(id);
            return Success(jjTemplateSignleViewModel);
        }

        /// <summary>
        /// 流程模板删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public async Task<IActionResult> DeleteTemplateById(int id)
        {
            await _jjFlowTemplateService.DeleteTemplate(id);
            return Success();
        }

        /// <summary>
        /// 流程模板新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveTemplate([FromBody] JJTemplateEditViewModel model)
        {
            var result = await _jjFlowTemplateService.SaveTemplate(model);
            if (result.IsSuccess)
            {
                return Success(result.Content, result.Message);
            }
            else
            {
                return Error(result.Message);
            }
        }

        /// <summary>
        /// 业务类型列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMappingPageList([FromQuery] JJMappingSearchCondition query)
        {
            var mappingPageList = await _jjFlowMappingService.GetMappingPageList(query);
            return Success(mappingPageList);
        }

        /// <summary>
        /// 业务类型 保存更新
        /// </summary>
        /// <param name="mapping"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveMapping([FromBody] JJMappingEditModel mapping)
        {
            var result = await _jjFlowMappingService.SaveMapping(mapping);
            if (result.IsSuccess)
            {
                return Success(result.Content, result.Message);
            }
            else
            {
                return Error(result.Message);
            }
        }

        /// <summary>
        /// 流程变量列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDictCodePageList([FromQuery] JJDictCodeSearchCondition query)
        {
            var pageListSearchResultVm = await _jjFlowDicCodeService.GetMappingPageList(query);
            return Success(pageListSearchResultVm);
        }

        /// <summary>
        /// 通过id获取明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDictCodeDetail([FromQuery] int id)
        {
            var jjFlowDictcodeVm = await _jjFlowDicCodeService.GetById(id);
            return Success(jjFlowDictcodeVm);
        }

        /// <summary>
        /// 流程变量保存  更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveDictCode([FromBody] JJDictCodeEditModel model)
        {
            var result = await _jjFlowDicCodeService.SaveDictCode(model);
            if (result.IsSuccess)
            {
                return Success(result.Content, result.Message);
            }
            else
            {
                return Error(result.Message);
            }
        }

        /// <summary>
        /// 流程变量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public async Task<IActionResult> DeleteDictCodeById(int id)
        {
            var result = await _jjFlowDicCodeService.DeleteDictCode(id);
            if (result.IsSuccess)
            {
                return Success(result.Content, result.Message);
            }
            else
            {
                return Error(result.Message);
            }
        }

        /// <summary>
        /// 工作流审批单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInstancePageList([FromQuery] JJInstanceSearchCondition query)
        {
            var responseResult = await _jjFlowService.GetInstancePageList(query);
            return Success(responseResult);
        }

        /// <summary>
        /// BPMXML-通过流程模板id获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DegineBPMXMLDetail([FromQuery] int id)
        {
            var responseResult = await _jjFlowBpmXmlService.GetDegineXMLDetail(id);
            return Success(responseResult);
        }

        /// <summary>
        /// 流程BPM设计保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveBPMDesign([FromBody] JJFlowDesignEditModel model)
        {
            await _jjFlowBpmXmlService.SaveBPMXML(model);
            return Success();
        }

        /// <summary>
        /// 用户是否有审核数据权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CheckUserPower([FromQuery] CheckQueryRequest request)
        {
            var userPowerResponse = await _jjFlowService.CheckUserPower(request);
            return Success(userPowerResponse);
        }
    }
}